package cn.com.zero.sample.trade.customer.controller;

import cn.com.zero.file.client.OSSTemplate;
import cn.com.zero.file.constants.FileUploadConstant;
import cn.com.zero.file.service.IFileService;
import cn.com.zero.file.util.FileUtil;
import cn.com.zero.file.vo.FileInfo;
import com.aliyun.oss.model.CannedAccessControlList;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description 文件接口示例-阿里云
 *          oss还有很多其他功能，若是使用的时候OssTemplate没有接口，可以通过OssClient自己写，获取OssClient代码： OSS ossClient = ossTemplate.getOssClient();（多例）
 * @createTime 2023/3/14 13:25
 */
@RestController
@RequestMapping("/file/oss")
@ConditionalOnProperty(name = "zero.file.type", havingValue = FileUploadConstant.FILE_TYPE_ALIYUN)
public class FileOSSController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private IFileService fileService;
    private OSSTemplate ossTemplate;


    @Resource
    public void setFileService(IFileService fileService) {
        this.fileService = fileService;
    }

    @Resource
    public void setOssTemplate(OSSTemplate ossTemplate) {
        this.ossTemplate = ossTemplate;
    }


    // 文件上传
    @PostMapping("/upload")
    public void uploadPicture(@RequestParam(value = "multipartFile") MultipartFile multipartFile) {
        String relativePath = "public/pic/";
        FileInfo fileInfo = fileService.upload(multipartFile, relativePath);
        log.info("文件上传完成,详细信息：{}", fileInfo);
        //  直接通过URL下载文件，URL参考： https://bucket-custom.oss-cn-chengdu.aliyuncs.com/public/pic/10591036628a460f92cf5643862b42cf.jpg
    }

    // 文件上传到私有存储桶
    @PostMapping("/uploadPrivate")
    public void uploadPrivatePicture(@RequestParam(value = "multipartFile") MultipartFile multipartFile) {
        String relativePath = "test/pic/";
        // oss的私有存储桶名
        String bucketName = "bucket-oss-private";
        // 若默认的是私有存储桶
//        String bucketName = ossTemplate.getBucketName();

        FileInfo fileInfo = fileService.upload(multipartFile, bucketName, relativePath);
        log.info("文件上传完成,详细信息：{}", fileInfo);

        // 下载方式： 从服务端下载， 或者获取限时签名URL
    }

    // 上传私有文件  不管存储桶权限是否私有，这样上传都是私有文件
    @PostMapping("/uploadPrivateOss")
    public void uploadPrivateOss(@RequestParam("file") MultipartFile file) {
        String relativePath = "private/test/pic/";
        String relativeFilePath = FileUtil.getRelativeFilePath(file, relativePath); // private/test/pic/文件名.jpg
        ossTemplate.upload(relativeFilePath, file, CannedAccessControlList.Private);
        log.info("文件上传完成，文件路径：{}", relativeFilePath);
    }


    // 压缩并上传图片
    @PostMapping("/uploadCompress")
    public void uploadCompress(@RequestParam(value = "multipartFile") MultipartFile multipartFile) {
        String relativePath = "test/pic/";
        FileInfo fileInfo = fileService.uploadImage(multipartFile, ossTemplate.getBucketName(), relativePath, 100, 100);
        log.info("文件上传完成,详细信息：{}", fileInfo);
    }

    // 删除文件
    @DeleteMapping("/delete")
    public void delete(@RequestParam("relativeFilePath") String relativeFilePath) {
        if (fileService.isExist(relativeFilePath)) {
            log.info("文件[{}]存在，开始删除文件。。。", relativeFilePath);
            fileService.delete(relativeFilePath);// 可以不判断文件是否存在
            log.info("文件[{}]存在，删除文件完成。。。", relativeFilePath);
        } else {
            log.info("文件[{}]不存在，删除失败", relativeFilePath);
        }
    }

    // 下载私有文件
    @PostMapping("/download")
    public org.springframework.core.io.Resource download(@RequestParam("relativeFilePath") String relativeFilePath) {
        String buckName = ossTemplate.getBucketName();
        return fileService.downloadFile(buckName, relativeFilePath);
    }

    // 下载私有文件
    @PostMapping("/download2")
    public String download2(@RequestParam("relativeFilePath") String relativeFilePath) {
        String buckName = ossTemplate.getBucketName();
        return fileService.downloadFileToBase64(buckName, relativeFilePath);
    }


    /**
     * 压缩生成小图 并存到文件件服务器
     *
     * @param bucketName       原始图片的存储空间
     * @param relativeFilePath 原始图片相对路径
     */
    @PostMapping("/compressImgSave")
    public void compressImgSave(@RequestParam("bucketName") String bucketName, @RequestParam("relativeFilePath") String relativeFilePath) {

        // 小图的存储空间
        String targetBucketName = "bucket-oss-private";
        // 小图的路径
        String targetObjectName = "compressPic/" + FileUtil.getRelativeFilePath(FilenameUtils.getExtension(relativeFilePath), null);

        ossTemplate.compressImgBucket(bucketName, relativeFilePath, targetBucketName, targetObjectName, 100, 100);

        log.info("小图生成完成,小图相对路径：{}", targetObjectName);
    }


    /**
     * 获取私有图片签名
     *
     * @param bucketName       私有图片的存储空间
     * @param relativeFilePath 图片相对路径
     * @param expireMin        签名失效时间，单位分
     * @param style            图片处理参数，为null时，表示不做处理直接返回；
     *                         不为null示例：  将图片缩放为固定宽高100 px后，再旋转90°： "image/resize,m_fixed,w_100,h_100/rotate,90"
     * @return 签名URL
     */
    @PostMapping("/getPrivateImgPresignedUrl")
    public URL getPrivateImgPresignedUrl(@RequestParam("bucketName") String bucketName,
                                         @RequestParam("relativeFilePath") String relativeFilePath,
                                         @RequestParam("expireMin") Integer expireMin,
                                         @RequestParam(value = "style", required = false) String style) {
        return ossTemplate.getPrivateImgPresignedUrl(bucketName, relativeFilePath, expireMin, style);
    }


}
